import asyncio

""" 
tcp 服务端-协程异步读写
"""
Server_IP = "127.0.0.1"
Server_Port = 9966

async def tcp_echo_client():
    reader, writer = await asyncio.open_connection(Server_IP, Server_Port)
    transport = writer.get_extra_info('transport')
    while True:
        try:
            # 1.读取输入
            input_msg = input("请输入要发送的数据：")
            if input_msg in ("exit", "quit", "q"):
                print("退出")
                break

            # 2.发送
            writer.write(input_msg.encode())
            await writer.drain()

            # 3.接收
            data = await reader.read(1024)
            print(f"recv: {data.decode()}")
            # 4.检查连接是否关闭
            if not data:
                print("socket 连接已关闭")
                break

        except asyncio.IncompleteReadError:
            print("服务端已断开连接")
            break

    print("Close the connection")
    writer.close()
    await writer.wait_closed()


async def main():
    await tcp_echo_client()


if __name__ == "__main__":
    asyncio.run(main())
